import 'dart:convert';

class ChatDataParser {
  static ChatStreamMessage parseStreamData(String rawData) {
    try {
      // 解析 JSON 数据
      final jsonData = json.decode(rawData);

      // 提取文本内容
      String text = '';
      bool isFinished = false;

      if (jsonData is Map<String, dynamic>) {
        // 处理 output 数据
        if (jsonData.containsKey('output')) {
          final output = jsonData['output'];
          if (output is Map<String, dynamic>) {
            // 处理 thoughts 数组
            if (output.containsKey('thoughts') && output['thoughts'] is List) {
              final thoughts = output['thoughts'] as List;
              for (var thought in thoughts) {
                if (thought is Map<String, dynamic>) {
                  if (thought.containsKey('response') && thought['response'] is String) {
                    text += thought['response'];
                  } else if (thought.containsKey('observation') && thought['observation'] is String) {
                    text += thought['observation'];
                  }
                }
              }
            }

            // 处理直接的文本内容
            if (output.containsKey('text') && output['text'] is String) {
              text += output['text'];
            }

            // 检查是否完成
            if (output.containsKey('finish_reason')) {
              isFinished = output['finish_reason'] != 'null';
            }
          }
        }
      }

      return ChatStreamMessage(
        content: text.isNotEmpty ? text : rawData,
        isComplete: isFinished,
        rawContent: rawData
      );
    } catch (e) {
      // 如果解析失败，返回原始数据
      return ChatStreamMessage(
        content: rawData,
        isComplete: false,
        rawContent: rawData
      );
    }
  }
}

class ChatStreamMessage {
  final String content;
  final bool isComplete;
  final String rawContent;

  ChatStreamMessage({
    required this.content,
    required this.isComplete,
    required this.rawContent,
  });
}
